#!/usr/bin/env bash

# Copyright 2024 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetesValidating:
- name: registry-secret-address.deckhouse.io
  group: main
  namespace:
    labelSelector:
      matchLabels:
        kubernetes.io/metadata.name: d8-system
  labelSelector:
    matchLabels:
      name: deckhouse-registry
  rules:
  - apiGroups:   [""]
    apiVersions: ["v1"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["secrets"]
    scope:       "Namespaced"
EOF
}

function __main__() {
  secretName=$(context::jq -r '.review.request.object.metadata.name')
  secretNs=$(context::jq -r '.review.request.object.metadata.namespace')
  if [[ "$secretName" == "deckhouse-registry" ]]; then
    if [[ "$secretNs" == "d8-system" ]]; then
      addr=$(context::jq -r '.review.request.object.data.address')
      if [[ -z "$addr" ]] || [[ "$addr" == "null" ]]; then
        cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":false, "message":"Registry address is required." }
EOF
        return 0
      fi
    fi
  fi

  cat <<EOF > "$VALIDATING_RESPONSE_PATH"
{"allowed":true}
EOF
}

hook::run "$@"
